package ru.ognick.option;

import ru.ognick.locale.ILocale;
import ru.ognick.locale.Locale;
import ru.ognick.logic.Praxis;
import ru.ognick.logic.Praxis.PraxisType;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;

public class BundleEditor {
	final private Praxis praxis;
	final private LinearLayout layout;
	final private static ILocale L = Locale.get();
	
	BundleEditor(Praxis praxis, LinearLayout layout){
		this.praxis = praxis;
		this.layout = layout;
	}
	
	public Praxis getPraxis() {
		return praxis;
	}
	public LinearLayout getLayout() {
		return layout;
	}
	
	private int getIntValue(String caption){
		String value = ((EditText) layout.findViewWithTag(caption.toUpperCase())).getText().toString();
		try {
			int result = Integer.valueOf(value); 
			return (result < 0)?0:result;
		}
		catch (NumberFormatException e) {
			return 0;
		}
	}
	
	
	public void save() {
		String[] types = Praxis.praxisTypeStringArray();
		PraxisType praxisType = null;
		for (String type : types) {
			RadioButton radioButton =  (RadioButton) layout.findViewWithTag(type.toUpperCase());
			if (radioButton.isChecked())
				praxisType = L.G_Praxis(type);
		}
		assert (praxisType != null);
		
		String title = ((EditText) layout.findViewWithTag("Title".toUpperCase())).getText().toString();
		if ("".equals(title)) praxisType = PraxisType.passive;
		String content = ((EditText) layout.findViewWithTag("Content".toUpperCase())).getText().toString();
		int timeSpan = getIntValue("Time");	
		int preTime = getIntValue("PreTime");
		int periodSpeak = getIntValue("Period speak");
		String media = ((Button) layout.findViewWithTag("media_button".toUpperCase())).getText().toString();
		if ("".equals(media)) media = null;
		
		praxis.savePraxis(
				praxisType, 
				title, 
				content, 
				timeSpan, 
				preTime, 
				periodSpeak, 
				media
		);
	
	}

}
